package cn.edu.zafu.bigdata.x.yaojy;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class UDPTimeServer {
    private  static final int PORT = 9876;
    public static void main(String[] args) {
        try(DatagramSocket socket = new DatagramSocket(PORT)){
            byte[] buffer = new byte[1024];
            while(true){
                DatagramPacket packet = new DatagramPacket(buffer,buffer.length);
                socket.receive(packet);
                String clientMessage = new String(packet.getData(),0,packet.getLength());
                System.out.println("Receive request from" + packet.getAddress().getAddress() + ":" + clientMessage);
                String currentTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                byte[] sendData = currentTime.getBytes();
                InetAddress clientAddress = packet.getAddress();
                int clientPort = packet.getPort();
                DatagramPacket responsePacket = new DatagramPacket(sendData,sendData.length,clientAddress,clientPort);
                socket.send(responsePacket);
                System.out.println("Sent time:" + currentTime + "to" + clientAddress.getAddress());
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
